﻿using System;
using Animoso.Data;
using NHibernate;
using NHibernate.Criterion;

namespace Animoso.Domain.Data
{
    public class LabelRepository : BaseRepository<Label>, ILabelRepository
    {
        public string GetTextByLabel(string name)
        {
            using(ISession session = SessionProvider.GetSession())
            {
                Label label = session.CreateCriteria(typeof (Label))
                    .Add(Expression.Eq("Name", name)).UniqueResult<Label>();

                if(label == null)
                {
                    label = new Label()
                                {
                                    Name = name,
                                    Text = ""
                                };
                    Add(label);
                }

                return label.Text;
            }
        }

        public void SetLabel(string name, string value)
        {
            using (ISession session = SessionProvider.GetSession())
            {
                Label label = session.CreateCriteria(typeof(Label))
                    .Add(Expression.Eq("Name", name)).UniqueResult<Label>();

                if (label == null)
                {
                    label = new Label()
                    {
                        Name = name,
                        Text = value
                    };
                    Add(label);
                }
                else
                {
                    label.Text = value;
                    Save(label);
                }
            }
        }
    }
}